package CAD.shujuku;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
/**
 * 这个类用来提供JDBC的工具类
 * @author Administrator
 *
 */
public class JDBCUtils {
    //1.私有化构造函数，外界无法直接创建对象
    private JDBCUtils(){

    }

    static ResourceBundle rb = null;
    static {
        //读取属性文件
        rb = ResourceBundle.getBundle("jdbc");
    }

    //2.提供公共的，静态的，getConnection方法，用来给外界提供数据库连接
    public static Connection getConnection(){
        try {
            //2.1注册驱动
            Class.forName(rb.getString("driverClass"));
            //2.2获取数据库连接
            String url = rb.getString("jdbcUrl");
            String user = rb.getString("user");
            String password = rb.getString("password");
            Connection conn = DriverManager.getConnection(url, user, password);
            return conn;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //3.提供公共的，静态的，close方法，用来释放资源
    public static void close(ResultSet rs,Statement st,Connection conn){
        //3.1非空判断，防止空指针异常
        //3.2手动置为空，保证完全释放
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                rs = null;
            }
        }
        if(st != null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                st = null;
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                conn = null;
            }
        }

    }
}


